//
//  MYAFNetworking.m
//  QA
//
//  Created by Yoga on 2017/4/25.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "MYAFNetworking.h"
#import "NSString+PPTAdditions.h"

static NSTimeInterval TimeOut = 30;

@implementation MYAFNetworking

- (void)printURLWithURL:(NSString *)url parameters:(NSDictionary *)parameters {
    NSLog(@"URL:%@%@",BASE_URL, url);
    NSLog(@"parameters:%@", parameters);
}
#pragma mark - 缓存
+ (NSString *)cacheDiskPath {
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/ModelCache"];
    return (path);
}
+ (NSString *)getCachePath:(id)parameters url:(NSString *)URLString {
    return [NSString stringWithFormat:@"%@-%@",URLString,parameters];
}
+ (void)saveCache:(NSString *)savePath cache:(id)cache {
    if(!TextIsNotNil(savePath) || !cache) {
        return;
    }
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cache];
    NSString *filePath = [self cacheDiskPath];
    NSString *path = [filePath stringByAppendingPathComponent:[savePath md5]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager isExecutableFileAtPath:path]) {
        NSError *error = nil;
        if([fileManager removeItemAtPath:path error:&error]) {
            NSLog(@">>>remove file failed:%@", error.debugDescription);
        }
        return;
    }
    if(![fileManager fileExistsAtPath:filePath]) {
        if(![fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil]) {
            NSLog(@">>>carete directory failed at path:%@", filePath);
        }
    }
    if(![fileManager createFileAtPath:path contents:data attributes:nil]) {
        NSLog(@">>>carete file failed at path:%@", path);
    }
}
+ (id)returnCache:(NSString *)savePath {
    if(!savePath) {
        return (nil);
    }
    
    NSString *filePath = [self cacheDiskPath];
    NSString *path = [filePath stringByAppendingPathComponent:[savePath md5]];
    NSData *data = [NSData dataWithContentsOfFile:path];
    if(!data || ![data isKindOfClass:[NSData class]]) {
        return (nil);
    }
    id obj = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return (obj);
}

+ (void)POST:(NSString *)URLString
  parameters:(id)parameters
     success:(void (^)(NSURLSessionDataTask *, id))success
     failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError *))failure
 isNeedCache:(BOOL)isNeed {
    
    if (!parameters) {
        parameters = [NSMutableDictionary dictionary];
    }
//    NSString * token = [UserInfo shareInstance].user.token;
//    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]initWithDictionary:parameters];
//    if (token != nil){
//        [parameter setObject:token forKey:@"token"];
//    }
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString * token = [UserInfo shareInstance].user.token;
    [session.requestSerializer setValue:token forHTTPHeaderField:@"token"];
    URLString = [NSString stringWithFormat:@"%@%@", BASE_URL, URLString];
    session.requestSerializer.timeoutInterval = TimeOut;
    
    if (isNeed) {
        NSString *path = [self getCachePath:parameters url:URLString];
        id obj = [self returnCache:path];
        if (obj) {
            success(nil, obj);
        }
    }
    
    [session POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSLog(@"POST Request sucess");
        if (isNeed) {
            NSString *path = [self getCachePath:parameters url:URLString];
            [self saveCache:path cache:responseObject];
        }
        success(task, [responseObject mj_JSONObject]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"POST error:%@ reason:%@",error.localizedDescription, error.localizedFailureReason);
        failure(task,error);
    }];
}
#pragma mark -
+ (void)POSTKuaiDi100:(NSString *)URLString
           parameters:(id)parameters
              success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
              failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError * error))failure {
    if (!parameters) {
        parameters = [NSMutableDictionary dictionary];
    }
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFHTTPRequestSerializer serializer];
    //    AFHTTPRequestSerializer
    [session.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [session.requestSerializer setStringEncoding:NSUTF8StringEncoding];
    session.requestSerializer.timeoutInterval = TimeOut;
    session.responseSerializer.acceptableContentTypes = [[NSSet alloc] initWithObjects:
                                                         @"application/json",
                                                         @"application/soap+xml",
                                                         @"text/html",
                                                         @"text/xml",
                                                         @"text/json",
                                                         @"text/javascript", nil];
   
    [session POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSLog(@"POST Request sucess");
        success(task, [responseObject mj_JSONObject]);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"POST error:%@ reason:%@",error.localizedDescription, error.localizedFailureReason);
        failure(task,error);
    }];
    
}
+ (void)POST:(NSString *)URLString
  parameters:(id)parameters
     success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
     failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError * error))failure {
    if (!parameters) {
        parameters = [NSMutableDictionary dictionary];
    }
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString * token = [UserInfo shareInstance].user.token;
    [session.requestSerializer setValue:token forHTTPHeaderField:@"token"];
    URLString = [NSString stringWithFormat:@"%@%@", BASE_URL, URLString];
    session.requestSerializer.timeoutInterval = TimeOut;
    session.responseSerializer.acceptableContentTypes = [[NSSet alloc] initWithObjects:
                                                         @"application/json",
                                                         @"application/soap+xml",
                                                         @"text/html",
                                                         @"text/xml",
                                                         @"text/json",
                                                         @"text/javascript", nil];
   

    [session POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSLog(@"POST Request sucess");
        success(task, [responseObject mj_JSONObject]);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"POST error:%@ reason:%@",error.localizedDescription, error.localizedFailureReason);
        failure(task,error);
    }];
}

+ (void)GET:(NSString *)URLString
 parameters:(id)parameters
    success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
    failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session willChangeValueForKey:@"timeoutInterval"];
    [session didChangeValueForKey:@"timeoutInterval"];
    session.requestSerializer.timeoutInterval = TimeOut;
    session.responseSerializer.acceptableContentTypes = [[NSSet alloc] initWithObjects:
                                                         @"application/json",
                                                         @"application/soap+xml",
                                                         @"text/html",
                                                         @"text/xml",
                                                         @"text/json",
                                                         @"text/javascript", nil];
//    URLString = [NSString stringWithFormat:@"%@%@",BASE_URL,URLString];
    if (![URLString hasPrefix:@"http"]) {
        URLString = [NSString stringWithFormat:@"%@%@", BASE_URL, URLString];
    }

    [session GET:URLString parameters:parameters progress:nil success:success failure:failure];
}

/**
 *  @brief  单图上传
 */
+ (void)UPLoad:(NSString *)URLString
        images:(id)image
      progress:(nullable void (^)(NSProgress * _Nonnull))progress
       success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session.requestSerializer setValue:[UserInfo shareInstance].user.token forHTTPHeaderField:@"token"];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",BASE_URL, URLString];
    
    [session POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *imageData =  UIImageJPEGRepresentation(image, 0.7);
        //使用日期生成图片名称
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *fileName =  [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        
        [formData appendPartWithFileData:imageData name:@"name" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(task,responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(task, error);
    }];
}

+ (void)Upload:(NSString *)url
       Imagess:(id)imageArray
       success:(void (^)(NSURLSessionDataTask *task, id responseObject,NSString *imageUrl ))success
       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session.requestSerializer setValue:[UserInfo shareInstance].user.token forHTTPHeaderField:@"token"];
    
    NSString *  URLString = [NSString stringWithFormat:@"%@%@",BASE_URL,url];
    
    [session POST:URLString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSMutableArray *arr = [NSMutableArray array];
        if ([imageArray isKindOfClass:[UIImage class]]) {
            [arr addObject:imageArray];
        }else if ([imageArray isKindOfClass:[NSArray class]]){
            [arr addObjectsFromArray:imageArray];
        }
        
        for (int i = 0; i < arr.count; i++)
        {
            UIImage *sourceImage =arr[i] ;
            NSData *imageData =  UIImageJPEGRepresentation(sourceImage, 0.7);
            
            //使用日期生成图片名称
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            
            NSString *fileName =  [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
            
            [formData appendPartWithFileData:imageData name:@"name[]" fileName:fileName mimeType:@"image/png"];
            
        }
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(task,responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(task, error);
    }];
    
}

/**
 *  单文件上传
 */
+ (void)uploadfileUrl:(NSString *)url
          filePath:(NSString *)filePath
          progress:(void (^)(NSProgress * _Nonnull uploadProgress))progress
           success:(void (^)(NSURLSessionDataTask *task, id responseObject,NSString *fileUrl ))success
           failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",BASE_URL, url];
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    [sessionManager.requestSerializer setValue:[UserInfo shareInstance].user.token forHTTPHeaderField:@"token"];
    
    NSString *fileName = [[filePath componentsSeparatedByString:@"/"] lastObject];
    
    [sessionManager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath] name:@"name[]" fileName:fileName mimeType:@"application/octet-stream" error:nil];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(task,responseObject,nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(task, error);
        }
    }];
}

/**
 *  先保留下载
 */
+ (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSString *)request
                                    completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler    {
    
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    NSString * token = [UserInfo shareInstance].user.token;
    
    [session.requestSerializer setValue:token     forHTTPHeaderField:@"token"];
    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:request]];
    NSURLSessionDownloadTask *downloadTask  =[session downloadTaskWithRequest:req progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"File downloaded to:==== %@", filePath);
        if (error) {
            NSLog(@"error ====%@",error.localizedDescription);
        }
        completionHandler(response,filePath,error);
    }];
    [downloadTask resume];
    
    return downloadTask;
    
}




//NSString  to  NSJson
+(NSString*)DataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

/*!
 * @brief 把格式化的JSON格式的字符串转换成字典
 * @param jsonString JSON格式的字符串
 * @return 返回字典
 */
+ (NSDictionary *_Nullable)dictionaryWithJsonString:(NSString *_Nullable)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

@end
